import { useEffect, useState } from 'react';
import { getMetrics } from '../../api';
import { history } from 'umi';

type IData = Record<string, string[]>;

export default (props: {
  nodeName: string;
  metrics: string[];
  render: (data: IData) => JSX.Element;
}) => {
  const { nodeName, metrics, render } = props;

  const [data, setData] = useState<IData>();

  const getData = async (n: string, m: string[]) => {
    const res = await getMetrics([n], m);
    if (!res || !res.data) {
      return;
    }
    if (history.location.pathname === '/node') {
      setData(res?.data);
    }
  };

  useEffect(() => {
    getData(nodeName, metrics);
    const interval = setInterval(() => getData(nodeName, metrics), 5000);
    return () => {
      if (interval) clearInterval(interval);
    };
  }, [nodeName, metrics]);

  if (!data) return <div>---</div>;

  return render(data);
};
